package com.kime.email.book;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.Properties;

/**
 * Java 邮件开发详解
 * 使用自定义 Authenticator 类的方式向邮件服务器提交认证信息
 */
public class AuthenticatorDemo {

    public static void main(String[] args) throws Exception {
        String smtpServer = "smtp.163.com"; // 邮件服务器主机名
        String protocol = "smtp"; // 邮件传输协议
        String username = "kimewen@163.com"; // 登录用户名
        String password = "OTWWWGKLGSAFQPNE"; // 登录密码/授权码
        String from = "kimewen@163.com"; //发件人地址
        String to = "kimewen@qq.com"; // 收件人地址
        String subject = "authenticator demo"; // 邮件主题
        String body = "authenticator demo"; // 邮件内容

        // 创建 Session 对象
        Properties properties = new Properties();
        properties.setProperty("mail.transport.protocol", protocol);
        properties.setProperty("mail.host", smtpServer);
        properties.setProperty("mail.smtp.auth", "true");
        MyAuthenticator myAuthenticator = new MyAuthenticator(username, password);
        Session session = Session.getInstance(properties, myAuthenticator);
        session.setDebug(true);

        // 创建代表邮件的 MimeMessage 对象
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(from));
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        message.setSentDate(new Date());
        message.setSubject(subject);
        message.setText(body);
        // 保存并生成最终的邮件内容
        message.saveChanges();

        // Transport.send(message);
        Transport transport = session.getTransport();
        transport.connect();
        transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO));
        transport.close();
    }
}
